package com.jluzh10.learning.web.controller;

import com.jluzh10.learning.domain.Chapter;
import com.jluzh10.learning.domain.User;
import com.jluzh10.learning.service.ChapterService;
import com.jluzh10.learning.utils.ResponseData;
import com.jluzh10.learning.utils.qiniu.QiniuUtil;
import com.jluzh10.learning.web.converter.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author yzg
 * @create 2019/5/27
 * <p>
 * 章节
 */
@Controller
@RequestMapping("chapter")
public class ChapterController {

    private final ChapterService chapterService;

    @Autowired
    public ChapterController(ChapterService chapterService) {
        this.chapterService = chapterService;
    }

    /**
     * 根据课程id查询所有章节
     *
     * @param courseId 课程id
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData find(@RequestParam Integer courseId) {
        List<Chapter> chapters = chapterService.list(courseId);
        //设置视频地址
        for (Chapter chapter : chapters) {
            chapter.setVideo(QiniuUtil.getUrl(chapter.getVideo()));
        }
        return new ResponseData().success().data(chapters);
    }

    /**
     * 加载章节的详细信息
     *
     * @param chapterId 章节id
     * @return
     */
    @RequestMapping(value = "/{chapterId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseData findById(@PathVariable(value = "chapterId") int chapterId,
                                 @LoginUser User user) {
        if (user != null) {
            Chapter chapter = chapterService.findById(chapterId, user.getId());

            chapter.setVideo(QiniuUtil.getUrl(chapter.getVideo()));
            return new ResponseData().success().data(chapter);
        }
        return new ResponseData().fail();
    }

    /**
     * 用户进入学习章节界面
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "video/{courseId}/{chapterId}", method = RequestMethod.GET)
    public ModelAndView video(@PathVariable(value = "chapterId") int chapterId,
                              @PathVariable(value = "courseId") int courseId,
                              ModelAndView modelAndView, @LoginUser User user) {
        if (user != null) {
            modelAndView.addObject("chapterId", chapterId);
            modelAndView.addObject("courseId", courseId);
            modelAndView.setViewName("video");
        } else {
            modelAndView.setViewName("register");
        }
        return modelAndView;
    }
}
